package com.itheima.web.controller;


import com.itheima.domain.User;
import com.itheima.factory.BeanFactory;
import com.itheima.service.ModuleService;
import com.itheima.service.UserService;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/authentication/*")
public class AuthenticationServlet extends BaseServlet{
private   UserService userService = BeanFactory.getService("userService", UserService.class);
private  ModuleService moduleService = BeanFactory.getService("moduleService", ModuleService.class);


    /**
     * 处理登录请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //1.获取请求参数
            String username = req.getParameter("email");
            String password = req.getParameter("password");
            //2.调用service层方法获得user对象
            User user =  userService.login(username,password);
            //3.判断是否登录成功，页面往哪里跳转
            if (user != null){
              //4 如果登录成功，保存用户信息到session中，响应结果
                req.getSession().setAttribute("user",user);
             List<String> curls = moduleService.findPermissionByUserId(user.getId());
                req.getSession().setAttribute("curls",curls);
                //curls.stream().forEach(curl-> System.out.println(curl));

                String requestURI = (String) req.getSession().getAttribute("requestURI");
                if (!StringUtils.isBlank(requestURI)){
                    resp.sendRedirect(requestURI);
                }else {
                    resp.sendRedirect(req.getContextPath()+"/pages/main.html");
                }
            }else {
                resp.sendRedirect(req.getContextPath()+"/login,html");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //清空session
        req.getSession().invalidate();
        //跳往登入界面
        resp.sendRedirect(req.getContextPath()+"/login.html");
    }
}
